package com.climber.android.commonres.ui.preview

import android.Manifest
import android.text.TextUtils
import android.view.View
import androidx.lifecycle.Lifecycle
import com.bumptech.glide.Glide
import com.climber.android.commonres.R
import com.climber.android.commonres.helper.BottomSheetDialogHelper
import com.climber.android.commonres.ui.BaseMVPFragment
import com.climber.android.commonres.util.UIHelper
import com.climber.android.commonsdk.api.APIError
import com.climber.android.commonsdk.api.ApiObserver
import com.climber.android.commonsdk.util.DragCloseHelper
import io.ganguo.library.mvp.Config
import io.ganguo.library.mvp.http.RxSchedulers
import io.ganguo.library.mvp.ui.mvp.IPresenter
import io.ganguo.library.mvp.ui.mvp.di.component.AppComponent
import io.ganguo.library.mvp.util.*
import io.reactivex.Observable
import io.reactivex.ObservableSource
import io.reactivex.android.schedulers.AndroidSchedulers
import kotlinx.android.synthetic.main.com_fragment_media_preview_image.*
import uk.co.senab.photoview.PhotoViewAttacher
import java.io.File

/**
 * Created by Mikes at 2020-04-17 15:28
 */
class MediaImagePreviewFragment : BaseMVPFragment<IPresenter>(){
    private lateinit var dragCloseHelper : DragCloseHelper

    private val mMediaPreview by lazy {
        arguments?.getParcelable<MediaPreview>("mediaPreview")
    }

    override fun setupFragmentComponent(appComponent: AppComponent) {
    }

    override fun getLayoutResourceId(): Int = R.layout.com_fragment_media_preview_image

    override fun initView(view: View) {
        previewImageView.maximumScale = 15.0f
        previewImageView.minimumScale = 1.0f
        previewImageView.mediumScale = 5.0f

        dragCloseHelper = DragCloseHelper(mHostContext)
        dragCloseHelper.setShareElementMode(true)
        dragCloseHelper.setDragCloseViews(iPreviewFl, previewImageView)
        dragCloseHelper.setDragCloseListener(object : DragCloseHelper.DragCloseListener {
            override fun intercept(): Boolean {
                //默认false 不拦截 如果图片是放大状态，或者处于滑动返回状态，需要拦截
                return previewImageView.scale != 1.0f
            }

            override fun dragStart() {
                //拖拽开始。可以在此额外处理一些逻辑
            }

            override fun dragging(percent: Float) {
                //拖拽中。percent当前的进度，取值0-1，可以在此额外处理一些逻辑
            }

            override fun dragCancel() {
                //拖拽取消，会自动复原。可以在此额外处理一些逻辑
            }

            override fun dragClose(isShareElementMode: Boolean) {
                //拖拽关闭，如果是共享元素的页面，需要执行activity的onBackPressed方法，注意如果使用finish方法，则返回的时候没有共享元素的返回动画
                if (isShareElementMode) {
                    closePage()
                }
            }
        })

        iPreviewFl.bindDragHelper(dragCloseHelper)
    }

    override fun initListener() {
        previewImageView.setOnPhotoTapListener(object : PhotoViewAttacher.OnPhotoTapListener {

            override fun onPhotoTap(view: View, x: Float, y: Float) {
                closePage()
            }

            override fun onOutsidePhotoTap() {

            }
        })

        previewImageView.setOnLongClickListener {
            downloadPicture()

            true
        }
    }

    private fun closePage(){
        activity?.finish()
    }

    override fun initData() {
        val mediaPreview = mMediaPreview ?: return
        if(!TextUtils.isEmpty(mediaPreview.previewPath)){
            Glide.with(this)
                    .load(File(mediaPreview.previewPath))
                    .into(previewImageView)
        } else if(!TextUtils.isEmpty(mediaPreview.previewUrl)){
            Glide.with(this)
                    .load(mediaPreview.previewUrl)
                    .into(previewImageView)
        } else{
            Glide.with(this)
                    .load(R.drawable.com_image_rect_loading)
                    .into(previewImageView)
        }
    }

    private fun downloadPicture(){
        val mediaPreview = mMediaPreview ?: return

        var picUrl = ""
        if(!TextUtils.isEmpty(mediaPreview.previewPath)){
            picUrl = mediaPreview.previewPath
        } else if(!TextUtils.isEmpty(mediaPreview.previewUrl)){
            picUrl = mediaPreview.previewUrl
        }
        if(TextUtils.isEmpty(picUrl)){
            return
        }

        requestSinglePermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) {grant ->
            if(grant){
                BottomSheetDialogHelper.showOnlyTitleDialog(mHostContext, "保存图片？") { confirm ->
                    if(confirm){
                        doSavePicture(picUrl)
                    }
                }
            }
        }
    }

    private fun doSavePicture(picUrl : String){
        Observable.defer {
            ObservableSource<File>{ observer ->
                try {
                    val file = Glide.with(AppUtils.getApp())
                            .download(picUrl)
                            .submit()
                            .get()
                    observer.onNext(file)
                } catch (e: Exception) {
                    observer.onError(RuntimeException("download image fail : ", e))
                }
            }
        }
                .compose(RxSchedulers.networkRequest())
                .doOnSubscribe{
                    UIHelper.showLoading(mHostContext)
                }
                .subscribeOn(AndroidSchedulers.mainThread())
                .`as`(RxLifecycleUtils.bindUntilEvent(this, Lifecycle.Event.ON_DESTROY))
                .subscribe(object : ApiObserver<File>(){
                    override fun success(file: File) {
                        UIHelper.hideLoading()

                        val saveSuccess = BitmapUtils.copyCacheImageToLocal(AppUtils.getApp(), file, Config.getImagePath())
                        if(saveSuccess){
                            ToastHelper.toastMessage("图片已保存")
                        } else{
                            ToastHelper.toastMessage("保存失败")
                        }
                    }

                    override fun dealError(apiError: APIError) {
                        super.dealError(apiError)
                        UIHelper.hideLoading()

                        ToastHelper.toastMessage("保存失败")
                    }
                })
    }
}